package com.jinkaimen.kqb.ui.activity.addmerchant;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.retrofit.RequestUtils;
import com.ht.baselibs.retrofit.bean.RequestParam;
import com.ht.baselibs.retrofit.converter.fastjson.FastJsonConverterFactory;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.AbDateUtil;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.DateUtils;
import com.ht.baselibs.utils.DeviceUtils;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.api.FileApi;
import com.jinkaimen.kqb.application.AppApplication;
import com.jinkaimen.kqb.bean.AuStepBean;
import com.jinkaimen.kqb.bean.BizShopBean;
import com.jinkaimen.kqb.bean.SearchShopBean;
import com.jinkaimen.kqb.constant.HttpConfig;
import com.jinkaimen.kqb.manager.ApiManager;
import com.jinkaimen.kqb.thread.CompressPhotoThread;
import com.jinkaimen.kqb.ui.weiget.CustomPopwindow;
import com.jinkaimen.kqb.ui.weiget.DialogUtils;
import com.jinkaimen.kqb.ui.weiget.photopicker.ImageCaptureManager;
import com.jinkaimen.kqb.utils.PermissionUtils;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.ht.baselibs.utils.SharedPreferencesUtils.put;

public class IdentificationShopStep1Activity extends BaseActivity {

    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CAMERA_CODE = 2;

    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/LICENCE.jpg";
    public static final String IDENTIFICATION_SETTLEMENT_TYPE_IS_PUBLIC = "identification_settlement_type_is_public";
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;


    private String mSelectCityCode;
    private TextView mLocationView;
    private String mSelectCityName;
    private TextView mPublicView;
    private TextView mPrivateView;
    private boolean isPublic;
    private EditText mShortNameView;
    private EditText mAddressView;
    private ImageView mLicenceView;
    private View mPublicContainnerView;
    private long mShopId;
    private DatePickerDialog mDatePickerDialog;
    private int mStartYear;
    private int mStartMonth;
    private int mStartDay;

    private int mEndYear;
    private int mEndMonth;
    private int mEndDay;
    private TextView mStartDateView;
    private TextView mEndDateView;
    private TextView mShopNoView;
    private long mUserId;
    private String shortName;
    private String districtName;
    private String address;
    private int isPublicTemp = 0;
    private long createTime;
    private long updateTime;
    private String districtCode;
    private String licenceID;
    private boolean isUpdate;
    private boolean canEdit = true;
    private TextView mNextButton;
    File file;
    private ImageCaptureManager captureManager;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        if (canEdit) {
            mTitleBarView.setLeftBtnIcon(View.GONE)
                    .setTitleText("填写商铺资料");
//                    .addActions(
//                    new TitleBarView.Action("上一步") {
//                        @Override
//                        public void performAction(View view) {
//                            Bundle bundle = new Bundle();
//                            bundle.putLong("report_shop_id", mShopId);
//                            bundle.putBoolean("canEdit", true);
//                            bundle.putLong("report_account_id", mUserId);
//                            ActivityUtils.startActivityAndFinish(IdentificationShopStep1Activity.this, RegisterActivity.class, bundle);
//                        }
//                    }
//            );
        } else {
            mTitleBarView.setTitleText("商铺资料").addActions(
                    new TitleBarView.Action("下一步") {
                        @Override
                        public void performAction(View view) {
                            Bundle bundle = new Bundle();
                            bundle.putBoolean("canEdit", false);
                            bundle.putLong("report_account_id", mUserId);
                            bundle.putLong("report_shop_id", mShopId);
                            ActivityUtils.startActivityAndFinish(IdentificationShopStep1Activity.this, IdentificationShopStep2Activity.class, bundle);
                        }
                    }
            );
        }

    }

    @Override
    protected int initContentView() {
        return R.layout.activity_identification_shop_step1_add_merchant;
    }

    @Override
    protected void initIntentData(Intent callIntent) {
        mShopId = callIntent.getLongExtra("report_shop_id", 0);
        mUserId = callIntent.getLongExtra("report_account_id", 0);
        canEdit = callIntent.getBooleanExtra("canEdit", true);
    }

    @Override
    protected void initChildView() {
//        file = new File(Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH + mShopId);
//        DirUtils.delFolder(file.getPath());

        mLicenceView = (ImageView) findViewById(R.id.iv_activity_identification_shop_step1_licence);
        mShortNameView = (EditText) findViewById(R.id.et_activity_identification_shop_step1_short_name);
        mLocationView = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_location);
        mAddressView = (EditText) findViewById(R.id.et_activity_identification_shop_step1_address);

        mPublicView = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_shop_settlement_type_public);
        mPrivateView = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_shop_settlement_type_private);
//此逻辑处理图片回填
        String path = SharedPreferencesUtils.getString("lic_photo_path" + mShopId, "");
        if (!TextUtils.isEmpty(path)) {
            isUpdate = true;
            Glide.with(this)//
                    .load(path)//
                    .skipMemoryCache(true)//
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(mLicenceView);
        }

        mPublicContainnerView = findViewById(R.id.ll_activity_identification_shop_step1_public);
        mShopNoView = (TextView) findViewById(R.id.et_activity_identification_shop_no);
        mStartDateView = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_start_date);
        mEndDateView = (TextView) findViewById(R.id.tv_activity_identification_shop_step1_end_date);
        mNextButton = (TextView) findViewById(R.id.btn_activity_identification_shop);

        DoCanEdit(canEdit);

    }

    private void DoCanEdit(Boolean canEdit) {
        mShortNameView.setFocusable(canEdit);
        mShortNameView.setFocusableInTouchMode(canEdit);

        mAddressView.setFocusable(canEdit);
        mAddressView.setFocusableInTouchMode(canEdit);

//        mPublicView.setFocusable(canEdit);
//        mPublicView.setFocusableInTouchMode(canEdit);
//
//        mPrivateView.setFocusable(canEdit);
//        mPrivateView.setFocusableInTouchMode(canEdit);

        mLicenceView.setFocusable(canEdit);
        mLicenceView.setFocusableInTouchMode(canEdit);

        mShopNoView.setFocusable(canEdit);
        mShopNoView.setFocusableInTouchMode(canEdit);

        mStartDateView.setFocusable(canEdit);
        mStartDateView.setFocusableInTouchMode(canEdit);

        mEndDateView.setFocusable(canEdit);
        mEndDateView.setFocusableInTouchMode(canEdit);

        mNextButton.setVisibility(canEdit ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void initChildData() {
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_camera);
//        Bitmap mLicence = BitmapFactory.decodeFile(file.getPath());
//        mLicenceView.setImageBitmap(mLicence == null ? bitmap : mLicence);
        Calendar calendar = Calendar.getInstance();
        mStartYear = mEndYear = calendar.get(Calendar.YEAR);
        mStartMonth = mEndMonth = calendar.get(Calendar.MONTH);
        mStartDay = mEndDay = calendar.get(Calendar.DAY_OF_MONTH);
//        mNextButton.setClickable(true);
        showLoadingDialog();
        ApiManager.getApi().searchShopInfo(
                "INV_HSY001010",
                mUserId
        ).enqueue(new NetCallBack<SearchShopBean>() {
            @Override
            protected void onSuccess(Call<SearchShopBean> call, Response<SearchShopBean> response) {
                BizShopBean bizShopBean = new BizShopBean();
                try {
                    bizShopBean = response.body().appBizShop;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                DoBackfillInfo(bizShopBean);
            }


            @Override
            protected boolean isNullNeedCallback() {
                return true;
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    @Override
    protected void setChildViewListener() {
        findViewById(R.id.rl_activity_identification_shop_step1_select_location).setOnClickListener(this);
        findViewById(R.id.btn_activity_identification_shop).setOnClickListener(this);
        mPublicView.setOnClickListener(this);
        mPrivateView.setOnClickListener(this);

        findViewById(R.id.rl_activity_identification_shop_step1_start_date).setOnClickListener(this);
        findViewById(R.id.rl_activity_identification_shop_step1_end_date).setOnClickListener(this);

        findViewById(R.id.iv_activity_identification_shop_step1_licence).setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_activity_identification_shop:
                String shopName = mShortNameView.getText().toString();
                String shopNameNew = stringFilter(shopName);
                String address = mAddressView.getText().toString();
                String licenceStartDate = mStartDateView.getText().toString().trim();
                String licenceEndDate = mEndDateView.getText().toString().trim();
                String licenceNO = mShopNoView.getText().toString().trim();

                if (TextUtils.isEmpty(shopName)) {
                    UIUtils.showToast("请输入店铺简称");
                    return;
                }
                if (shopName.length() < 2) {
                    UIUtils.showToast("店铺简称最少为2个字,请重新输入");
                    return;
                }
                if (shopName.length() > 10) {
                    UIUtils.showToast("店铺简称最多为25个字,请重新输入");
                    return;
                }
                if (!shopName.equals(shopNameNew)) {
                    UIUtils.showToast("店铺简称只能输入汉字,字母和数字,请重新输入");
                    return;
                }


                if (mSelectCityCode == null) {
                    UIUtils.showToast("请选择所在地");
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    UIUtils.showToast("请输入详细地址");
                    return;
                }
                if (address.length() < 5) {
                    UIUtils.showToast("详细地址最少五个字,请重新输入");
                    return;
                }


                HashMap<String, Object> requestDataMap = new HashMap<>();
                requestDataMap.put("id", mShopId);
                requestDataMap.put("shortName", shopName);
                requestDataMap.put("districtCode", mSelectCityCode);
                requestDataMap.put("address", address);
                requestDataMap.put("isPublic", isPublic ? 1 : 0);
                requestDataMap.put("fileA", "LICENCE");

                if (isPublic) {
                    if (TextUtils.isEmpty(licenceStartDate)) {
                        UIUtils.showToast("请选择起始日期");
                        return;
                    }
                    if (TextUtils.isEmpty(licenceEndDate)) {
                        UIUtils.showToast("请选择结束日期");
                        return;
                    }
                    long startTime = AbDateUtil.getDateByFormat(licenceStartDate, AbDateUtil.dateFormatYMD).getTime();
                    long endTime = AbDateUtil.getDateByFormat(licenceEndDate, AbDateUtil.dateFormatYMD).getTime();
                    if (endTime < startTime) {
                        UIUtils.showToast("起始、结束日期填写错误,请重新输入");
                        return;
                    }
                    if (TextUtils.isEmpty(licenceNO)) {
                        UIUtils.showToast("请输入营业执照号");
                        return;
                    }

                    if (isPublic && !isUpdate) {
                        UIUtils.showToast("请上传营业执照照片");
                        return;
                    }
                }

                requestDataMap.put("licenceNO", mShopNoView.getText().toString());
                String startDate = mStartDateView.getText().toString();
                requestDataMap.put("licenceStartDate", TextUtils.isEmpty(startDate) ? null : startDate);
                String endDate = mEndDateView.getText().toString();
                requestDataMap.put("licenceEndDate", TextUtils.isEmpty(endDate) ? null : endDate);

                showLoadingDialog();
                String requestData = JSON.toJSONString(requestDataMap, false);
                LogUtils.error(requestData);
                Map<String, RequestBody> params = RequestUtils.createPartMap(
                        new RequestParam("serviceCode", "INV_HSY001002"),
                        new RequestParam("requestData", requestData),
                        new RequestParam(HttpConfig.GlobalParam.APP_TYPE, "android"),
                        new RequestParam(HttpConfig.GlobalParam.V, "v1.8"),
                        new RequestParam(HttpConfig.GlobalParam.TIME_STAMP, DateUtils.getCurrentTime()),
                        new RequestParam(HttpConfig.GlobalParam.DEVICE_ID, DeviceUtils.getDeviceId() + "")
                );


                String path = SharedPreferencesUtils.getString("lic_photo_path" + mShopId, "");
                if (!TextUtils.isEmpty(path)) {
//                    if (!TextUtils.isEmpty(path)) {
//                        String[] pathSplit = path.split("@");
//                        if ((mShopId + "").equals(pathSplit[1])) {
//                            path = pathSplit[0];
//                        }
//                    }
                    File file = new File(path);
                    params.putAll(RequestUtils.createPartMap(new RequestParam("fileA", file)));
                }

                Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                retrofitBuilder.client(builder.build())
                        .baseUrl(HttpConfig.BASE_URL) //这里的baseUrl不用设置
                        .addConverterFactory(FastJsonConverterFactory.create())
                        .build()
                        .create(FileApi.class).uploadFileAndForm(params).enqueue(new NetCallBack<BaseGetBean>() {
                    @Override
                    protected void onSuccess(Call<BaseGetBean> call, Response<BaseGetBean> response) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("report_account_id", mUserId);
                        bundle.putLong("report_shop_id", mShopId);
                        bundle.putBoolean("isPublic", isPublic);

//                        file.deleteOnExit();
//                        mNextButton.setClickable(false);
                        AppApplication.putTempData("isPublic", isPublic ? "1" : "0");
                        ActivityUtils.startActivityAndFinish(IdentificationShopStep1Activity.this, IdentificationShopStep2Activity.class, bundle);
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                break;
            case R.id.rl_activity_identification_shop_step1_select_location:
                if (!canEdit) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString(SelectLocationActivity.CURRENT_LOCATION, mSelectCityName);
                ActivityUtils.startActivityForResult(this, SelectLocationActivity.class, bundle, SelectLocationActivity.REQUEST_CODE_SELECT_LOCATION_CITY);
                break;
            case R.id.tv_activity_identification_shop_step1_shop_settlement_type_public:
                if (!canEdit) {
                    return;
                }
                isPublic = true;
                Ispublic();
                break;
            case R.id.tv_activity_identification_shop_step1_shop_settlement_type_private:
                if (!canEdit) {
                    return;
                }
                isPublic = false;
                NOPublic();
                break;
            case R.id.iv_activity_identification_shop_step1_licence:
                try {
                    InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!canEdit) {
                    return;
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.rl_activity_identification_shop_step1_start_date:
                if (!canEdit) {
                    return;
                }
                mDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                    }
                }, mStartYear, mStartMonth, mStartDay);
                mDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "清除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mStartDateView.setText("");
                    }
                });

                mDatePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDatePickerDialog.getDatePicker();
                        mStartYear = datePicker.getYear();
                        mStartMonth = datePicker.getMonth();
                        mStartDay = datePicker.getDayOfMonth();
                        int month = mStartMonth + 1;
                        if (month >= 10) {
                            mStartDateView.setText(mStartYear + "-" + month + "-" + (mStartDay > 10 ? mStartDay : "0" + mStartDay));
                        } else {
                            mStartDateView.setText(mStartYear + "-0" + month + "-" + (mStartDay > 10 ? mStartDay : "0" + mStartDay));
                        }
                    }
                });
                mDatePickerDialog.show();
                break;
            case R.id.rl_activity_identification_shop_step1_end_date:
                if (!canEdit) {
                    return;
                }
                mDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        mEndYear = year;
                        mEndMonth = monthOfYear;
                        mEndDay = dayOfMonth;
                        int month = mStartMonth + 1;
                        if (month >= 10) {
                            mEndDateView.setText(mEndYear + "-" + month + "-" + (mEndDay > 10 ? mEndDay : "0" + mEndDay));
                        } else {
                            mEndDateView.setText(mEndYear + "-0" + month + "-" + (mEndDay > 10 ? mEndDay : "0" + mEndDay));
                        }
                    }
                }, mEndYear, mEndMonth, mEndDay);
                mDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "清除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mEndDateView.setText("");
                    }
                });

                mDatePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDatePickerDialog.getDatePicker();
                        mEndYear = datePicker.getYear();
                        mEndMonth = datePicker.getMonth();
                        mEndDay = datePicker.getDayOfMonth();
                        int month = mEndMonth + 1;
                        if (month >= 10) {
                            mEndDateView.setText(mEndYear + "-" + month + "-" + (mEndDay > 10 ? mEndDay : "0" + mEndDay));
                        } else {
                            mEndDateView.setText(mEndYear + "-0" + month + "-" + (mEndDay > 10 ? mEndDay : "0" + mEndDay));
                        }
                    }
                });
                mDatePickerDialog.show();
                break;
        }

    }

    private void Ispublic() {
        mPublicView.setBackgroundResource(R.drawable.shape_label_blue);
        mPrivateView.setBackgroundResource(R.drawable.shape_label_gray);
        mPublicView.setTextColor(Color.parseColor("#6284dd"));
        mPrivateView.setTextColor(Color.parseColor("#bebebe"));
        put(IDENTIFICATION_SETTLEMENT_TYPE_IS_PUBLIC, true);
        mPublicContainnerView.setVisibility(View.VISIBLE);
    }

    private void NOPublic() {
        mPublicView.setBackgroundResource(R.drawable.shape_label_gray);
        mPrivateView.setBackgroundResource(R.drawable.shape_label_blue);
        mPublicView.setTextColor(Color.parseColor("#bebebe"));
        mPrivateView.setTextColor(Color.parseColor("#6284dd"));
        put(IDENTIFICATION_SETTLEMENT_TYPE_IS_PUBLIC, false);
//        mPublicContainnerView.setVisibility(View.GONE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture();
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SelectLocationActivity.REQUEST_CODE_SELECT_LOCATION_CITY:
                    mSelectCityCode = data.getStringExtra("cityCode");
                    if (mSelectCityCode != null) {
                        mSelectCityName = data.getStringExtra("cityName") + "/" + data.getStringExtra("areaName");
                        mLocationView.setText(mSelectCityName);
                    }
                    break;
                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    SharedPreferencesUtils.put("lic_photo_path" + mShopId, filePath);
                    showLoadingDialog();
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    SharedPreferencesUtils.put("lic_photo_path" + mShopId, picturePath);
                    showLoadingDialog();
                    break;
            }
        }
    }

    private void DoBackfillInfo(BizShopBean bizShopBean) {

        shortName = bizShopBean.shortName;
        districtName = bizShopBean.districtName;
        try {
            String[] split = districtName.split("\\|");
            if (split.length == 3) {
                districtName = split[1] + "/" + split[2];
            } else if (split.length == 2) {
                districtName = split[0] + "/" + split[1];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        address = bizShopBean.address;
        isPublicTemp = bizShopBean.isPublic;
        licenceID = bizShopBean.licenceNO;
        createTime = bizShopBean.licenceStartDate;
        updateTime = bizShopBean.licenceEndDate;
        mSelectCityCode = bizShopBean.districtCode;
        mShortNameView.setText(shortName);
        mLocationView.setText(districtName);
        mAddressView.setText(address);
        isPublic = isPublicTemp == 1 ? true : false;
        if (isPublic) {

            Ispublic();
        } else {
            NOPublic();
        }

        mShopNoView.setText(licenceID);
        if (createTime != 0) {
            mStartDateView.setText("20" + DateUtils.formatDateTimeHMS(createTime).substring(0, 8));
        }
        if (updateTime != 0) {
            mEndDateView.setText("20" + DateUtils.formatDateTimeHMS(updateTime).substring(0, 8));
        }


    }

    private void takePicture() {
        DialogUtils.createPopwindow(IdentificationShopStep1Activity.this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                try {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);

                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                    startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);

                } catch (Exception e) {
                    UIUtils.showToast("无法启用系统相机");
                    e.printStackTrace();
                }

            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CAMERA_CODE);
            }
        }).showAtBottom(mTitleBarView);
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH+mShopId);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//        startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case 200: //图片
                int type = (int) msg.obj;
                switch (type) {
                    case 0:
                        isUpdate = true;
                        Glide.with(this)//
                                .load(Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(mLicenceView);
                        hideLodingDialog();
                        break;
                    case 1:
                        isUpdate = true;
                        String path = SharedPreferencesUtils.getString("lic_photo_path" + mShopId, "");
//                        if (!TextUtils.isEmpty(path)) {
//                            String[] pathSplit = path.split("@");
//                            path = pathSplit[0];
//                        } else {
//                            path = "";
//                        }
                        Glide.with(this)//
                                .load(path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(mLicenceView);
                        hideLodingDialog();
                        break;
                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String tempShortName = mShortNameView.getText().toString().trim();
        String tempLocation = mLocationView.getText().toString().trim();
        String tempAddress = mAddressView.getText().toString().trim();
        int tempIsPublic = isPublic ? 1 : 0;

        AppApplication.putTempData("tempShortName", tempShortName);
        AppApplication.putTempData("tempLocation", tempLocation);
        AppApplication.putTempData("tempAddress", tempAddress);
        AppApplication.putTempData("tempIsPublic", tempIsPublic);

        AppApplication.putTempData("mSelectCityCode", mSelectCityCode);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mNextButton.setClickable(true);
    }

    /**
     * 匹配正则表达式
     *
     * @param str
     * @return
     */
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字-
        //String   regEx  =  "[^a-zA-Z0-9-u4E00-u9FA5]";
        String regEx = "[^a-zA-Z0-9\u4e00-\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
}
